<template>
  <Header />
  <main class="ShopCar">
    <van-swipe-cell v-for="(item,index) in ItemList" :key="index">
      <van-card 
        :num="item.num"
        :price="item.price"
        :title="item.name"
        class="goods-card"
        :thumb="item.img"
      />
      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" @click="Delete(item.itemID)"/>
      </template>
    </van-swipe-cell>
    <van-submit-bar
      :loading="buying"
      button-text="提交订单"
      @submit="onSubmit"
      style="margin-bottom:50px;"
    />
  </main>
  <Footer />
</template>

<script>
import Footer from "./Footer";
import Header from "./Header";
export default {
  name: "ShopCar",
  components: {
    Footer,
    Header,
  },
  data(){
    return{
      ItemList:[],
      buying:false
    }
  },
  methods: {
    getShopCar:async function(){
      this.axios.get("getShopCar.php").then(response=>{
      let data=response.data
      data.forEach(element => {
        let info={
          num:element.num,
          user:element.UserID
        }
        let id=element.GoodsID
        let num=element.num
        console.log(num)
        this.axios.get("selectItemByID.php?id="+id).then(res=>{
          (res.data).forEach(element => {
            info['itemID']=element.itemId
            info['name']=element.itemName
            info['price']=num*element.price
            info['img']=element.itemimg
            this.ItemList.push(info)
          });
        })
        console.log(this.ItemList)
      });
    })
    .catch(e=>{
      console.log(e)
    })
    },
    Delete:function(itemID){
      this.$dialog.confirm({
        title:"移除购物车",
        message:"您确定要删除吗?"
      })
      .then(()=>{
        this.axios.get("deleteItem.php?itemID="+itemID).then((response)=>{
          if(response.data==="OK")
            this.$toast.success("删除成功")
            window.location.reload()
        })
      })
      .catch((e)=>{
        console.log(e)
      })
    },
    getBudge:function(){
      this.axios.get("extra/getTotal.php").then(response=>{
        this.badges=(response.data)[0].count
        console.log(this.badges)
      })
    },
    onSubmit:function(){
      this.buying=true
      this.$toast.loading({
        message: '购买中...',
        forbidClick: true,
        duration:500000
      })
      setTimeout(() => {
        this.$toast.clear()
        this.$toast("购买成功")
        this.buying=false
      }, 1000);
    }
  },
  mounted() {
    this.$toast.loading({
      message: "加载中...",
      forbidClick: true,
      duration: 500,
    });
  },
  created(){
    this.$store.commit("init")
    this.getBudge()
    this.getShopCar()
  }
};
</script>

<style scoped>
.ShopCar {
  width: 100%;
  height: 85vh;
  margin-top: 50px;
}
.van-button--normal{
  height: 100%;
}
</style>
